﻿using LCL;
using LCL.CodeEngine;
using LCL.Config;
using LCL.LData;
using LCL.Tools.Build;
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Windows.Forms;
using ICSharpCode.TextEditor;
using ICSharpCode.TextEditor.Document;

namespace LCL.Tools.WinFrm {
    public partial class FrmTemplateCodeBuilder : Form {
        private TableModel table = null;
        private string Templatefilename;
        private string codeFileExt = "";
        private TextEditorControl txtTemplate = null;
        private TextEditorControl txtContent = null;
        private DbConfigInfo config = null;
        public FrmTemplateCodeBuilder(string tablename) {
            InitializeComponent();
            config=DbConfig.GetConfig();
            table=UIFactory.UIDb().GetTableInfo(AppConfig.GetInstance().DbName, tablename);

            txtTemplate=new TextEditorControl();
            txtTemplate.ContextMenuStrip=this.templateMenu;
            txtTemplate.Dock=DockStyle.Fill;
            txtTemplate.Document.HighlightingStrategy=HighlightingStrategyFactory.CreateHighlightingStrategy("HTML");
            txtTemplate.Encoding=Encoding.Default;
            txtTemplate.IsIconBarVisible=false;
            txtTemplate.ShowInvalidLines=false;
            txtTemplate.ShowSpaces=false;
            txtTemplate.ShowTabs=false;
            txtTemplate.ShowEOLMarkers=false;
            txtTemplate.ShowVRuler=false;
            txtTemplate.Font=new System.Drawing.Font("新宋体", 9f);

            txtContent=new TextEditorControl();
            txtContent.ContextMenuStrip=this.codeMenu;
            txtContent.Dock=DockStyle.Fill;
            txtContent.Document.HighlightingStrategy=HighlightingStrategyFactory.CreateHighlightingStrategy("C#");
            txtContent.Encoding=Encoding.Default;
            txtContent.IsIconBarVisible=false;
            txtContent.ShowInvalidLines=false;
            txtContent.ShowSpaces=false;
            txtContent.ShowTabs=false;
            txtContent.ShowEOLMarkers=false;
            txtContent.ShowVRuler=false;
            txtContent.Font=new System.Drawing.Font("新宋体", 9f);

            this.groupBox3.Controls.Add(txtTemplate);
            this.tabPage2.Controls.Add(txtContent);
        }
        public void InitFrm() {
            this.dataGridView1.AutoGenerateColumns=false;
            this.treeView1.ImageList=this.imageList1;
            this.groupBox3.Text="";
            this.groupBox2.Text="表详细信息";
            UIFactory.UIFact().BinTemplateTree(this.treeView1);
            if(table!=null) {
                this.groupBox3.Text=table.TableName+table.TableNameRemark;
                this.groupBox3.Tag=table;
                this.groupBox2.Text=table.TableName+table.TableNameRemark+"表详细信息";
                this.groupBox2.Tag=table;
                this.dataGridView1.DataSource=table.Columns;
            }
        }
        private void treeView1_DoubleClick(object sender, EventArgs e) {
            try {
                this.保存ToolStripMenuItem.Enabled=true;
                TempNode tempNode = (TempNode)this.treeView1.SelectedNode;
                string nodeID = tempNode.NodeID;
                string nodeType = tempNode.NodeType;
                string filePath = tempNode.FilePath;

                if(nodeType=="tt"||nodeType=="cmt") {
                    Templatefilename=Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filePath);
                    StreamReader streamReader = new StreamReader(Templatefilename, Encoding.Default);
                    string text = streamReader.ReadToEnd();
                    streamReader.Close();
                    this.txtTemplate.Document.HighlightingStrategy=HighlightingStrategyFactory.CreateHighlightingStrategy("HTML");
                    this.txtTemplate.Text=text;
                    this.groupBox3.Text=Templatefilename;
                    tabControl1.SelectedIndex=0;
                }
            } catch(Exception ex) {
                this.txtTemplate.Text="加载模板失败"+ex.Message;
            }
        }
        private void but_Run_Click(object sender, EventArgs e) {
            GC.Collect();
            Run();
            GC.Collect();
        }
        public void Run() {
            try {
                if(table==null) {
                    MessageBox.Show("请选择表", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    return;
                }
                string text = this.txtTemplate.Text;
                if(text.Trim()=="") {
                    MessageBox.Show("模板内容为空,请先在模板管理器里选择模板", "提示",
                        MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    return;
                }
                if(Templatefilename==null) {
                    Templatefilename=Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Template\\TemplateFile\\temp~.cmt");
                    File.WriteAllText(Templatefilename, text, Encoding.UTF8);
                } else {
                    File.WriteAllText(Templatefilename, text, Encoding.UTF8);
                }
            } catch(Exception ex) {
                MessageBox.Show("模板格式有误:"+ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            string strContent = "";
            CodeInfo codeinfo = new CodeInfo();
            try {

                BuilderTemp builderTemp = new BuilderTemp(AppConfig.GetInstance().DbName,
                    table.TableName, Templatefilename, "table");
                codeinfo=builderTemp.GetCode();
                if(codeinfo.ErrorMsg!=null&&codeinfo.ErrorMsg.Length>0) {
                    strContent=string.Concat(new string[]{
                        codeinfo.Code,
                        Environment.NewLine,
                        "/*----------代码生成时出现错误:------",
                        Environment.NewLine,
                        codeinfo.ErrorMsg,
                        "*/"
                    });
                } else {
                    strContent=codeinfo.Code;
                }
            } catch(Exception ex) {
                MessageBox.Show("代码转换失败！"+ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            try {
                codeFileExt=Path.GetExtension(codeinfo.FileExtension).ToLower();
                //https://www.cnblogs.com/maijin/articles/4660682.html
                switch(codeFileExt) {
                    case "php":
                    case ".php":
                        txtContent.Document.HighlightingStrategy=HighlightingStrategyFactory.CreateHighlightingStrategy("PHP");
                        break;
                    case "js":
                    case ".js":
                        txtContent.Document.HighlightingStrategy=HighlightingStrategyFactory.CreateHighlightingStrategy("JavaScript");
                        break;
                    case "htm":
                    case ".htm":
                    case "html":
                    case ".html":
                        txtContent.Document.HighlightingStrategy=HighlightingStrategyFactory.CreateHighlightingStrategy("HTML");
                        break;
                    case "java":
                    case ".java":
                        txtContent.Document.HighlightingStrategy=HighlightingStrategyFactory.CreateHighlightingStrategy("Java");
                        break;
                    case "xml":
                    case ".xml":
                        txtContent.Document.HighlightingStrategy=HighlightingStrategyFactory.CreateHighlightingStrategy("XML");
                        break;
                    case "sql":
                    case ".sql":
                        txtContent.Document.HighlightingStrategy=HighlightingStrategyFactory.CreateHighlightingStrategy("TSQL");
                        break;
                    default:
                        txtContent.Document.HighlightingStrategy=HighlightingStrategyFactory.CreateHighlightingStrategy("C#");
                        break;
                }
                this.txtContent.Text=Utils.ClearBlankLine(strContent);
                //this.tabControl1.SelectedIndex=1;
            } catch(Exception ex) {
                MessageBox.Show("编辑器错误！"+ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
        }

        #region templateMenu
        private void 剪切ToolStripMenuItem1_Click(object sender, EventArgs e) {
            string str = txtTemplate.ActiveTextAreaControl.SelectionManager.SelectedText;
            if(str=="")
                return;
            Clipboard.SetText(str);
            txtTemplate.ActiveTextAreaControl.SelectionManager.RemoveSelectedText();
        }

        private void 粘贴ToolStripMenuItem1_Click(object sender, EventArgs e) {
            string str = Clipboard.GetText();
            txtTemplate.ActiveTextAreaControl.TextArea.InsertString(str);
            if(txtTemplate.ActiveTextAreaControl.SelectionManager.HasSomethingSelected)
                txtTemplate.ActiveTextAreaControl.SelectionManager.RemoveSelectedText();
        }

        private void 删除ToolStripMenuItem2_Click(object sender, EventArgs e) {
            string str = txtTemplate.ActiveTextAreaControl.SelectionManager.SelectedText;
            if(str!="")
                txtTemplate.ActiveTextAreaControl.SelectionManager.RemoveSelectedText();
        }
        private void menu_Copy_Click(object sender, EventArgs e) {
            string selectedText = this.txtTemplate.ActiveTextAreaControl.SelectionManager.SelectedText;
            Clipboard.SetDataObject(selectedText);
        }
        private void 保存ToolStripMenuItem_Click(object sender, EventArgs e) {
            try {
                string text = this.txtTemplate.Text;
                if(!string.IsNullOrWhiteSpace(text)||!string.IsNullOrWhiteSpace(this.Templatefilename)) {
                    File.WriteAllText(this.Templatefilename, text, Encoding.UTF8);
                    MessageBox.Show("保存成功!");
                }
            } catch(Exception ex) {
                MessageBox.Show("保存失败!"+ex.Message);
            }
        }
        private void 另存为ToolStripMenuItem_Click(object sender, EventArgs e) {
            try {
                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.Title="模板另存为";
                string text = this.txtTemplate.Text;
                DialogResult dialogResult = saveFileDialog.ShowDialog(this);
                if(dialogResult==DialogResult.OK) {
                    string fileName = saveFileDialog.FileName;
                    File.WriteAllText(fileName, text, Encoding.UTF8);
                }
            } catch(Exception ex) {
                MessageBox.Show("保存失败!"+ex.Message);
            }
        }

        public void Setsqltext(string msg) {
            this.groupBox3.Text="";
            this.txtTemplate.Document.HighlightingStrategy=HighlightingStrategyFactory.CreateHighlightingStrategy("SQL");
            this.txtTemplate.Text=msg;
            this.txtContent.Text="";
            this.保存ToolStripMenuItem.Enabled=false;
            this.but_Run.Enabled=false;

        }
        #endregion

        #region codeMenu
        private void 剪切ToolStripMenuItem_Click(object sender, EventArgs e) {
            string str = txtContent.ActiveTextAreaControl.SelectionManager.SelectedText;
            if(str=="")
                return;
            Clipboard.SetText(str);
            txtContent.ActiveTextAreaControl.SelectionManager.RemoveSelectedText();
        }
        private void 全选ToolStripMenuItem_Click(object sender, EventArgs e) {
            this.txtContent.ActiveTextAreaControl.SelectionManager.SetSelection(
                 txtContent.Document.OffsetToPosition(0),
                 txtContent.Document.OffsetToPosition(txtContent.Document.TextLength));

        }
        private void 复制ToolStripMenuItem_Click(object sender, EventArgs e) {
            string selectedText = this.txtContent.ActiveTextAreaControl.SelectionManager.SelectedText;
            if(selectedText=="")
                return;
            Clipboard.SetDataObject(selectedText);
        }
        private void 保存ToolStripMenuItem1_Click(object sender, EventArgs e) {
            try {
                //codeFileExt
                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.Title="保存当前代码";
                switch(codeFileExt) {
                    case "php":
                    case ".php":
                        txtContent.Document.HighlightingStrategy=HighlightingStrategyFactory.CreateHighlightingStrategy("PHP");
                        saveFileDialog.Filter="PHP files (*.php)|*.php|All files (*.*)|*.*";
                        break;
                    case "js":
                    case ".js":
                        txtContent.Document.HighlightingStrategy=HighlightingStrategyFactory.CreateHighlightingStrategy("JavaScript");
                        saveFileDialog.Filter="JavaScript files (*.js)|*.js|All files (*.*)|*.*";
                        break;
                    case "htm":
                    case ".htm":
                    case "html":
                    case ".html":
                        saveFileDialog.Filter="html files (*.html)|*.html|All files (*.*)|*.*";
                        break;
                    case "java":
                    case ".java":
                        saveFileDialog.Filter="java files (*.java)|*.java|All files (*.*)|*.*";
                        break;
                    case "xml":
                    case ".xml":
                        saveFileDialog.Filter="xml files (*.xml)|*.xml|All files (*.*)|*.*";
                        break;
                    default:
                        saveFileDialog.Filter="C# files (*.cs)|*.cs|All files (*.*)|*.*";
                        break;
                }
                DialogResult dialogResult = saveFileDialog.ShowDialog(this);
                if(dialogResult==DialogResult.OK) {
                    string fileName = saveFileDialog.FileName;
                    File.WriteAllText(fileName, this.txtContent.Text, Encoding.UTF8);
                }
            } catch(Exception ex) {
                MessageBox.Show("保存失败!"+ex.Message);
            }
        }
        private void 粘贴ToolStripMenuItem_Click(object sender, EventArgs e) {
            string str = Clipboard.GetText();
            txtContent.ActiveTextAreaControl.TextArea.InsertString(str);
            if(txtContent.ActiveTextAreaControl.SelectionManager.HasSomethingSelected)
                txtContent.ActiveTextAreaControl.SelectionManager.RemoveSelectedText();

        }
        private void 删除ToolStripMenuItem1_Click(object sender, EventArgs e) {
            string str = txtContent.ActiveTextAreaControl.SelectionManager.SelectedText;
            if(str!="")
                txtContent.ActiveTextAreaControl.SelectionManager.RemoveSelectedText();
        }
        #endregion

        #region templateAdminMenu
        string templatefolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Template\\TemplateFile");
        private void 刷新ToolStripMenuItem_Click(object sender, EventArgs e) {
            UIFactory.UIFact().BinTemplateTree(this.treeView1);
        }
        private void 打开所在文件夹ToolStripMenuItem_Click(object sender, EventArgs e) {
            try {
                Process.Start("explorer.exe", templatefolder);
            } catch {
                MessageBox.Show("打开目标文件夹失败，请手动打开该文件夹。");
            }
        }
        private void 文件夹ToolStripMenuItem_Click(object sender, EventArgs e) {
            try {
                TempNode tempNode = (TempNode)this.treeView1.SelectedNode;
                string text = tempNode.FilePath+"\\新文件夹";
                if(!Directory.Exists(text)) {
                    Directory.CreateDirectory(text);
                }
                TempNode tempNode2 = new TempNode("新文件夹");
                tempNode2.FilePath=text;
                tempNode2.NodeType="folder";
                tempNode2.ImageIndex=0;
                tempNode2.SelectedImageIndex=1;
                tempNode.Nodes.Add(tempNode2);
                tempNode.Expand();
                this.treeView1.SelectedNode=tempNode2;
                this.treeView1.LabelEdit=true;
                if(!tempNode2.IsEditing) {
                    tempNode2.BeginEdit();
                }
            } catch(Exception ex) {
                MessageBox.Show(ex.Message);
            }
        }
        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e) {
            try {
                TempNode tempNode = (TempNode)this.treeView1.SelectedNode;
                string arg_17_0 = tempNode.NodeID;
                string arg_1E_0 = tempNode.Text;
                string filePath = tempNode.FilePath;
                string nodeType = tempNode.NodeType;
                if((nodeType=="tt"||nodeType=="cmt"||nodeType=="aspx"||
                    nodeType=="cs"||nodeType=="vb")&&File.Exists(filePath)) {
                    File.Delete(filePath);
                }
                if(nodeType=="folder") {
                    DirectoryInfo directoryInfo = new DirectoryInfo(filePath);
                    if(directoryInfo.Exists) {
                        directoryInfo.Delete();
                    }
                }
                this.treeView1.Nodes.Remove(tempNode);
            } catch(Exception ex) {
                MessageBox.Show(ex.Message);
            }
        }
        private void 模板ToolStripMenuItem_Click(object sender, EventArgs e) {
            try {
                TempNode tempNode = (TempNode)this.treeView1.SelectedNode;
                string text = tempNode.FilePath+"\\新建模板.cmt";
                string text2 = "新建模板";
                text=this.GetFileName(tempNode.FilePath, text2, out text2);
                StreamWriter streamWriter = new StreamWriter(text, false, Encoding.UTF8);
                streamWriter.Close();
                TempNode tempNode2 = new TempNode(text2+".cmt");
                tempNode2.FilePath=text;
                tempNode2.NodeType="cmt";
                tempNode2.ImageIndex=2;
                tempNode2.SelectedImageIndex=2;
                tempNode.Nodes.Add(tempNode2);
                this.treeView1.SelectedNode=tempNode2;
                this.treeView1.LabelEdit=true;
                if(!tempNode2.IsEditing) {
                    tempNode2.BeginEdit();
                }
            } catch(Exception ex) {
                MessageBox.Show(ex.Message);
            }
        }
        private void 备份模板到ToolStripMenuItem_Click(object sender, EventArgs e) {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            DialogResult dialogResult = dialog.ShowDialog();
            if(dialogResult==DialogResult.OK) {
                string selectedPath = dialog.SelectedPath;
                this.CopyDirectory(templatefolder, selectedPath);
                MessageBox.Show("备份完成！");
                try {
                    new Process();
                    Process.Start("explorer.exe", selectedPath);
                } catch {
                    MessageBox.Show("打开目标文件夹失败，请手动打开该文件夹。");
                }
            }
        }
        public void CopyDirectory(string SourceDirectory, string TargetDirectory) {
            DirectoryInfo directoryInfo = new DirectoryInfo(SourceDirectory);
            DirectoryInfo directoryInfo2 = new DirectoryInfo(TargetDirectory);
            if(!directoryInfo.Exists) {
                return;
            }
            if(!directoryInfo2.Exists) {
                directoryInfo2.Create();
            }
            FileInfo[] files = directoryInfo.GetFiles();
            int num = files.Length;
            for(int i = 0; i<num; i++) {
                File.Copy(files[i].FullName, directoryInfo2.FullName+"\\"+files[i].Name, true);
            }
            DirectoryInfo[] directories = directoryInfo.GetDirectories();
            for(int j = 0; j<directories.Length; j++) {
                this.CopyDirectory(directories[j].FullName, directoryInfo2.FullName+"\\"+directories[j].Name);
            }
        }
        public string GetFileName(string path, string oldname, out string filename) {
            string text = path+"\\"+oldname+".cmt";
            filename=oldname;
            int num = 1;
            while(File.Exists(text)) {
                filename=oldname+num;
                text=path+"\\"+filename+".cmt";
                num++;
            }
            return text;
        }
        #endregion

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e) {
            switch(this.tabControl1.SelectedTab.Name) {
                case "代码":
                    this.txtContent.ActiveTextAreaControl.SelectionManager.SetSelection(
                    txtContent.Document.OffsetToPosition(0),
                    txtContent.Document.OffsetToPosition(txtContent.Document.TextLength));
                    string selectedText = this.txtContent.ActiveTextAreaControl.SelectionManager.SelectedText;
                    if(selectedText=="")
                        return;
                    Clipboard.SetDataObject(selectedText);
                    break;
            }
        }
    }

    public class TempNode : TreeNode {
        public string NodeID { get; set; }
        public string FilePath { get; set; }
        public string NodeType { get; set; }
        public string ParentID { get; set; }
        public TempNode() {

        }
        public TempNode(string NodeName) {
            base.Text=NodeName;
        }
    }


}



